package com.caisejingyu.whales.home.dialog

import android.os.Bundle
import android.os.CountDownTimer
import android.support.v4.app.DialogFragment
import android.view.View
import com.caisejingyu.whales.common.ui.SimpleFragment
import com.caisejingyu.whales.home.R
import com.caisejingyu.whales.home.common.ZXingUtils
import kotlinx.android.synthetic.main.fragment_qr_code.*

class QRCodeFragment : SimpleFragment() {
    private var countDownTimer: CountDownTimer? = null
    var content: String? = null
    var dialogFragment: DialogFragment? = null

    override fun init(savedInstanceState: Bundle?) {
        countDownTimer = object : CountDownTimer(30000, 500) {
            override fun onTick(millisUntilFinished: Long) {
                val intervalTime = millisUntilFinished / 1000
                qrIntervalText.text = String.format(getString(R.string.home_dialog_interval), intervalTime.toString())
            }

            override fun onFinish() {
                qrIntervalText.text = String.format(getString(R.string.home_dialog_interval), "0")
                countDownTimer?.cancel()
                dialogFragment?.dismiss()
            }
        }
        countDownTimer?.start()

        qrIntervalText.setOnClickListener {
            dialogFragment?.dismiss()
        }

        qrImageView.post {
            qrImageView.setImageBitmap(ZXingUtils.createQRImage(content, qrImageView.width, qrImageView.height))
        }
    }

    override fun layoutId(): Int {
        return R.layout.fragment_qr_code
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()
        dialogFragment?.dismiss()
    }

}